package com.example.quickleave;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.opencv.android.OpenCVLoader;

import java.util.ArrayList;
import java.util.List;

import de.timonknispel.ktloadingbutton.KTLoadingButton;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "main";

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        OpenCVLoader.initDebug();

        KTLoadingButton save = findViewById(R.id.saveBtn);
        Button returnBtn = findViewById(R.id.returnBtn);
        ImageView imageView = findViewById(R.id.pic1);

        String name = getIntent().getStringExtra("name");
        String type = getIntent().getStringExtra("type");
        String time_begin = getIntent().getStringExtra("time_begin");
        int days = getIntent().getIntExtra("days", 1);
        String reason = getIntent().getStringExtra("reason");
        String time_pass = getIntent().getStringExtra("time_pass");
        String instructor = getIntent().getStringExtra("instructor");
        boolean is_crop = getIntent().getBooleanExtra("is_crop", false);
        Bitmap bitmap = ImageProcessor.getBitmap(this, R.drawable.src);
        List<String> pic_paths = getIntent().getStringArrayListExtra("pics");
        List<Bitmap> pics = new ArrayList<>();
        assert pic_paths != null;
        for (String pic_path : pic_paths) {
            Log.i(TAG, pic_path);
            pics.add(BitmapFactory.decodeFile(pic_path));
        }
        Bitmap handled = ImageProcessor.handle(bitmap, name, type, time_begin, days, reason, time_pass, instructor, pics, is_crop);
        imageView.setImageBitmap(handled);

        save.setOnClickListener(v -> {
            save.startLoading();
            boolean b = ImageSaver.saveImageToGallery(this, handled);
            save.doResult(b, ktLoadingButton -> null);
        });

        returnBtn.setOnClickListener(v -> finish());
    }
}